import { createSlice } from "@reduxjs/toolkit";
import axios from 'axios';

// 创建 slice 对象
let slice = createSlice({
  //状态的名字
  name: 'todo',
  //状态的初始值
  initialState: [],
  //配置 reducer 的功能
  reducers: {
    //声明功能方法  dispatch({type: '', payload: [1,2,3,4,5]})   immer
    init: (state, action) => {
      //将 payload 中的数据, 全部压入到当前状态的数组中
      state.push(...action.payload);
    },
    //新增功能
    add: (state, action) => {
      //将 action.payload 的任务对象压入到 state 数组中
      state.push(action.payload);
    },
    // {type: 'todo/remove', payload: id}
    remove: (state, action) => {
      //删除指定 id 的任务对象  splice
      // //获取对应 id 的任务下标
      // let index = state.findIndex(item => item.id === action.payload);
      // //通过 splice 方法删除数组中指定 id 的任务
      // state.splice(index, 1);

      return state.filter(item => item.id !== action.payload);
    },
    // {type: 'todo/update', payload: data}
    update: (state, action) => {
      //获取指定 id 的任务的下标
      let index = state.findIndex(item => item.id === action.payload.id);
      //更新任务的完成状态
      state[index].done = action.payload.done;
    }
  }
});

//获取 slice 内部的 reducer 函数
let reducer = slice.reducer;

//获取 action creator
let {init, add, remove, update} = slice.actions;

//暴露
export default reducer;

//封装异步的 action creator
export let asyncGetTodos = () => {
  return async (dispatch) => {
    //发送 AJAX 请求
    let {data} = await axios.get('http://localhost:3001/todos')
    //更新状态
    dispatch(init(data));
  }
}

//发送请求新增任务
export let asyncAddTodo = (title) => {
  return async dispatch => {
    //新增
    let result = await axios.post('http://localhost:3001/todos', {title, done: false});
    //输出结果
    // console.log(result.data);
    dispatch(add(result.data));
  }
}

//发送请求删除任务
export let asyncRemove = (id) => {
  return async dispatch => {
    //发送请求
    let result = await axios.delete(`http://localhost:3001/todos/${id}`);
    //同步的更新 redux 中的状态
    dispatch(remove(id));// {type: 'todo/remove', payload: id}
  }
}

//发送请求更新任务的完成状态
export let asyncCheckTodo = ({id, done}) => {
  //返回异步的 action
  return async dispatch => {
    //发送请求
    let result = await axios.patch(`http://localhost:3001/todos/${id}`, {done: done});
    //更新 redux 中状态的值
    dispatch(update(result.data));// {type: 'todo/update', payload: result}
  } 
}